<template>
  <BaseTable
    class="table-style mt-2"
    bordered
    max-fill
    :loading="loading"
    :extra-height="64"
    column-code="000118"
    :scroll="{ x: 1000 }"
    :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
    :expanded-row-keys="expandedRowKeys"
    :data-source="dataSource"
  >
    <template #bodyCell="{ column, index, record }">
      <template v-if="column.dataIndex === 'link'">
        <div class="table-link"></div>
      </template>
      <template v-if="column.dataIndex === 'sfxm'">
        <EditCell title="药品名称">
          <SelectMedicine v-model:value="record.sfxm" :auto-focus="record.isNew && index > 0" @select="(selected) => onSelectMedicine(selected, record)" />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'yf'">
        <EditCell title="用法" :disabled="record.isChild">
          <SelectTable
            v-model:value="record.yf.fyff"
            :auto-focus="!record.isChild && record.isNew && focusCell === record.key + '用法'"
            :table-width="360"
            type="用法"
            @select="(selected) => onSelectWays(selected, record)"
          />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'pl'">
        <EditCell title="频次" :disabled="record.isChild">
          <SelectTable
            v-model:value="record.pl.pl"
            :auto-focus="!record.isChild && record.isNew && focusCell === record.key + '频率'"
            :table-width="360"
            type="频率"
            @select="(selected) => onSelectFrequency(selected, record)"
          />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'jlsl'">
        <EditCell title="剂量">
          <BaseInput
            v-model:value="record.jlsl"
            v-input:int
            v-input-selection
            :auto-focus="record.isNew && focusCell === record.key + '剂量'"
            :suffix="record.sfxm?.jldw"
            placeholder="请输入"
            @keydown.enter="focusCell = record.key + (record.isChild ? '总量' : '天数')"
            @blur="onCalc(record)"
          />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'cfts'">
        <EditCell title="天数" :disabled="record.isChild">
          <BaseInput
            v-model:value="record.cfts"
            v-input:int
            v-input-selection
            :auto-focus="record.isNew && focusCell === record.key + '天数'"
            suffix="天"
            placeholder="请输入"
            @keydown.enter="focusCell = record.key + '总量'"
            @blur="onDaysBlur(record)"
          />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'sl'">
        <EditCell title="总量">
          <BaseInput
            v-model:value="record.sl"
            v-input:int
            v-input-selection
            :auto-focus="record.isNew && focusCell === record.key + '总量'"
            :suffix="record.sfxm?.dw"
            placeholder="请输入"
            @keydown.enter="saveNewRows(true, record.isChild ? record.fkey : false)"
            @blur="editRow(record)"
          />
        </EditCell>
      </template>
      <template v-if="column.dataIndex === 'apportionmentAllowed'">
        <a-switch :checked="record.apportionmentAllowed" :disabled="record.isNew" :un-checked-value="0" :checked-value="1" @click="onSwitch(record)" />
      </template>
      <template v-if="column.dataIndex === 'yssm'">
        <EditCell title="医生说明">
          <a-input v-model:value="record.yssm" v-input-selection placeholder="请输入" @blur="editRow(record)" />
        </EditCell>
      </template>
      <template v-else-if="column.dataIndex === 'action'">
        <BaseButton v-if="record.isChild" confirm-text="作废子医嘱?" size="small" danger type="text" @click="onDeleteChild(record)"> 作废子医嘱 </BaseButton>
        <template v-else>
          <a-button type="link" size="small" :disabled="![2, 4, 5].includes(record?.sfxm?.xmlb)" @click="addChildRow(record)"> 子医嘱 </a-button>
          <a-divider type="vertical" />
          <BaseButton confirm-text="作废医嘱?" size="small" danger type="text" @click="onDelete(record)"> 作废 </BaseButton>
        </template>
      </template>
    </template>
    <template #footer>
      <div class="text-center sticky bottom-0">
        <a-button type="primary" class="mr-2" ghost :icon="h(PlusOutlined)" :disabled="!suitStore.currentSuit.tcid" @click="addRow()"> 新增一行 </a-button>
        <a-button type="primary" :icon="h(SaveOutlined)" :disabled="!isHaveNewRow()" @click="saveNewRows()"> 保存 </a-button>
      </div>
    </template>
  </BaseTable>
</template>
<script setup>
import { ref, h, watch, createVNode } from 'vue'
import { message } from 'ant-design-vue'
import { Modal } from 'ant-design-vue'
import { PlusOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { post } from '@/utils/request'
import useSuitStore from '../../workstation/store'

const emit = defineEmits(['success'])
const loading = ref(false)
const suitStore = useSuitStore()
const focusCell = ref('')
const expandedRowKeys = ref([])
const dataSource = ref([])
const generateRow = (isChild = false) => {
  return {
    id: '',
    fid: '',
    yf: {},
    pl: {},
    key: `row-key-${Math.random().toString().slice(2)}`,
    ...(!isChild && { children: [] }),
    isChild,
    isNew: true
  }
}
const isHaveNewRow = () => {
  return dataSource.value?.some((item) => item.isNew)
}

const saveNewRows = async (addNew, addChild) => {
  const newRows = dataSource.value.filter((item) => item.isNew)
  newRows.forEach((item) => {
    fetchSave(item, addNew, addChild)
  })
}

const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row, addNew = false, addChild = false) => {
  if (row.sfxm && row.pl.pl && row.jlsl && row.sl && row.cfts && row.yf.fyff) {
    if (!row.yf) {
      const confirm = await onShowConfirm()
      if (!confirm) return
    }
    const { code, msg } = await post('/outp/template/doAddClinicalOrderPackageItem', { tcid: suitStore.currentSuit.tcid, ...row })
    if (code !== 0) return message.error(msg || '操作失败')
    message?.destroy()
    message.success(row.isNew ? '新增成功' : '修改成功')
    await getData()
    if (addNew) {
      addChild ? addChildRow(dataSource.value.find((item) => item.key === addChild)) : addRow(dataSource)
    }
    emit('success')
  } else {
    message.destroy()
    message.error('请填写完整信息')
  }
}
const onShowConfirm = () => {
  return new Promise((resolve) => {
    Modal.confirm({
      title: '提示',
      okText: '确定',
      centered: true,
      width: 560,
      cancelText: '取消',
      content: createVNode('div', { style: 'margin:24px 0;font-size:15px' }, '用法为空，是否继续提交？'),
      onOk: () => resolve(true),
      onCancel: () => resolve(false)
    })
  })
}
//获取数据
const getData = async () => {
  loading.value = true
  const { data, code } = await post('/outp/template/getClinicalOrderPackageItemList', { tcid: suitStore.currentSuit.tcid, czcf: 1 })
  loading.value = false
  if (code !== 0) message.error('获取数据失败')
  if (data.length > 0) {
    expandedRowKeys.value = data.map((item) => 'row-key-' + item.id)
    dataSource.value = data.map((child) => ({
      ...child,
      yf: child.yf || {},
      pl: child.pl || {},
      key: 'row-key-' + child.id,
      children: child.children ? child.children.map((c) => ({ ...c, yf: c.yf || {}, pl: c.pl || {}, isChild: true, cfbh: 0, fkey: child.id, key: c.id })) : []
    }))
  } else {
    expandedRowKeys.value = []
    dataSource.value = []
  }
}
watch(
  () => suitStore.currentSuit.tcid,
  (val) => {
    val ? getData() : (dataSource.value = [])
  },
  {
    deep: true
  }
)
//选药
const onSelectMedicine = (medicine, row) => {
  row.sfxm = medicine
  row.jlsl = 1
  row.cfts = row.cfts || 1
  row.sl = 1
  focusCell.value = `${row.key}${row.isChild ? '剂量' : '用法'}`
  onCalc(row)
}
//选用法
const onSelectWays = (selected, row) => {
  row.yf = selected
  row?.children.length && row.children.forEach((item) => (item.yf = selected))
  focusCell.value = row.key + '频率'
  editRow(row)
}
//选频率
const onSelectFrequency = (selected, row) => {
  row.pl = selected
  row?.children.length && row.children.forEach((item) => (item.pl = selected))
  focusCell.value = row.key + '剂量'
  onCalc(row)
}

const onDelete = async (row) => {
  if (row.isNew) {
    const index = dataSource.value.findIndex((item) => item.key === row.key)
    dataSource.value.splice(index, 1)
  } else {
    fetchDelete(row)
  }
}
const onDeleteChild = async (row) => {
  if (row.isNew) {
    const fData = dataSource.value.find((item) => item.key === row.fkey)
    const index = fData.children.findIndex((item) => item.key === row.key)
    fData.children.splice(index, 1)
  } else {
    fetchDelete(row)
  }
}
const fetchDelete = async (row) => {
  const { code, msg } = await post('/outp/template/doDelClinicalOrderPackageItem', {
    bh: row.bh,
    tcid: suitStore.currentSuit.tcid,
    cjr: suitStore.currentSuit.cjr
  })
  if (code !== 0) return message.error(msg || '删除失败')
  message.success('删除成功')
  getData()
  emit('success')
}

//添加行
const addRow = () => {
  const newRow = generateRow()
  expandedRowKeys.value.push(newRow.key)
  dataSource.value.push(newRow)
}
//添加子医嘱
const addChildRow = (row) => {
  if (!row.sfxm || !row.yf || !row.pl || !row.sl || !row.cfts) return message.error('请填写主医嘱')
  const extendParams = { yf: row.yf, pl: row.pl, cfts: row.cfts }
  const newRow = generateRow(true)
  const addRow = { fkey: row.key, cfbh: row.cfbh, ...newRow, ...extendParams }
  row.isNew = true
  row.children.push(addRow)
}
const onDaysBlur = (row) => {
  row?.children.length && row.children.forEach((item) => (item.cfts = row.cfts))
  onCalc(row)
}
const onCalc = async (row) => {
  if (!row.cfts || !row.jlsl || !row.pl.pl || !row.sfxm) return
  const { data, code } = await post('/outp/mzys/calculateTheTotal', {
    cfts: row.cfts,
    jlsl: row.jlsl,
    pl: row.pl,
    sfxm: row.sfxm
  })
  if (code !== 0) return message.error('计算失败')
  row.sl = data
  editRow(row)
}
const onSwitch = async (row) => {
  const { code, msg } = await post('/outp/template/allocationAllowed', {
    apportionmentAllowed: row.apportionmentAllowed ? 0 : 1,
    id: row.id
  })
  if (code !== 0) return message.error(msg || '操作失败')
  getData()
}
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
